package com.yun.util.yun.config.filters;



import com.alibaba.druid.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "HostCleanFilter", urlPatterns = "/*")
public class HostCleanFilter implements Filter {

    FilterConfig filterConfig = null;

    @Autowired
    private Environment environment;

    private Logger logger = LoggerFactory.getLogger(HostCleanFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        logger.info("过滤器初始化");
        this.filterConfig = filterConfig;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        logger.info("执行过滤操作");
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse res = (HttpServletResponse) servletResponse;

        String method= req.getMethod();
        String requestHost = req.getHeader("host");
        String requestReferer=req.getHeader("referer");
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(req.getScheme()).append("://").append(req.getServerName());
        if(requestReferer != null && !requestReferer.equals("") ){
            if(requestReferer.lastIndexOf(String.valueOf(stringBuffer)) != 0){
                res.setStatus(403);
                return;
            }
        }
        if(environment.getProperty("whiteHost")!=null){
            if("OPTIONS".equals(method)){
                res.setStatus(403);
                return;
            }
            if (requestHost != null && !isRightHost(requestHost)) {
                res.setStatus(403);
                return;
            }
        }
        filterChain.doFilter(req, res);
    }

    @Override
    public void destroy() {
        logger.info("过滤器销毁");
        this.filterConfig = null;
    }

    /**
     * <p>Method: isRightHost </p>
     * <p>Description: 返回当前请求是否在白名单列表 </p>
     * <p>date: 2020/1/8 9:01 </p>
     * @author zhuyu[zhuyu@boco.com.cn]
     */
    public boolean isRightHost(String requestHost) {
        logger.info("请求host:"+requestHost);
        String whiteHost = environment.getProperty("whiteHost");
        String[] whiteHosts = whiteHost.split(",");
        boolean isRightHost = false;
        for(int i=0;i<whiteHosts.length;i++){
            if(StringUtils.equals(requestHost, whiteHosts[i])){
                isRightHost = true;
                break;
            }
        }
        return isRightHost;
    }

}